<template>
  <div class="setting-container">
    <div class="app-container">
      <!-- 卡片组件 -->
      <el-card class="box-card">
        <!-- 使用 Tabs 组件完成标签页布局 -->
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="first" class="tab-pane">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="addRoleBtn"
              >新增角色</el-button>
            </el-row>
            <!-- 使用 Table 组件实现用户角色的渲染 -->
            <el-table border style="width: 100%" :data="rolesList">
              <el-table-column type="index" label="序号" width="120" />
              <el-table-column label="角色名" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="setRoles(scope.row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRoles(scope.row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRoles(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination
              :current-page="query.page"
              :page-sizes="[10, 15, 20, 25]"
              :page-size="query.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" class="tab-pane">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" :model="formData" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit ? '编辑角色' : '新增角色'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="closeRoleFn"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="roleRules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>

        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="cancleRoles">取消</el-button>
            <el-button size="small" type="primary" @click="roleSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <!-- 分配权限弹框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="dialogVisible"
        width="50%"
        @close="roleDialogCloseFn"
      >
        <AssignPermission ref="assignPermission" :role-id="roleId" :permission-list="permissionList" :role-ids-list="roleIdsList" @close="roleDialogCloseFn" @confirm="confirmFn" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRolesAPI, getCompanyInfoAPI, addRoleAPI, getRoleIdAPI, updateRoleAPI, deleteRoleAPI, getPermissionListAPI, assignPermAPI } from '@/api'
import { mapGetters } from 'vuex'
import AssignPermission from './components/assignPermission.vue'
import { transTree } from '@/utils'
export default {
  components: {
    AssignPermission
  },
  data() {
    return {
      activeName: 'first',
      query: {
        page: 1, // 当前页面
        pagesize: 10 // 页面显示的条数
      },
      rolesList: [], // 角色列表
      total: 0, // 角色数据总条数
      formData: {},
      showDialog: false, // 控制弹框的隐藏和展示
      roleForm: {
        name: '',
        description: ''
      },
      // 添加角色验证
      roleRules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      isEdit: false, // 弹窗是新增/编辑-状态
      dialogVisible: false, // 分配权限 - 弹窗显示/隐藏
      roleId: 0, // 分配权限 - 保存当前角色id
      permissionList: [], // 权限点数组
      roleIdsList: [] // 某个角色的权限点数组
    }
  },
  computed: {
    ...mapGetters(['companyId'])
  },
  created() {
    // 角色列表
    this.getRolesListFn()
    // 公司信息
    this.getCompanyInfoFn()
    // 权限点 - 名字列表
    this.getPermissionListFn()
  },
  methods: {
    // 获取角色列表
    async getRolesListFn() {
      const res = await getRolesAPI(this.query)
      console.log(res)
      this.rolesList = res.data.rows
      this.total = res.data.total // 总数
    },
    // 获取公司的信息
    async getCompanyInfoFn() {
      const res = await getCompanyInfoAPI(this.companyId)
      console.log(res)
      this.formData = res.data
    },
    // 获取 - 权限点名字列表
    async getPermissionListFn() {
      const res = await getPermissionListAPI()
      this.permissionList = transTree(res.data, '0')
    },

    // 添加权限按钮
    async roleSubmit() {
      this.$refs.roleForm.validate(async valid => {
        if (!valid) return false
        if (this.isEdit) { // 编辑
          const res = await updateRoleAPI(this.roleForm)
          if (!res.success) return this.$message.error(res.message)
          this.$message.success(res.message)
        } else { // 新增
          const res = await addRoleAPI(this.roleForm)
          if (!res.success) return this.$message.error(res.message)
          this.$message.success(res.message)
        }
        this.getRolesListFn()
        this.showDialog = false
      })
    },
    // 取消权限按钮
    cancleRoles() {
      this.showDialog = false
    },

    // 每页显示的条数发生改变时触发
    handleSizeChange(pageSize) {
      this.query.pagesize = pageSize
      this.getRolesListFn()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(nowPage) {
      this.query.page = nowPage
      this.getRolesListFn()
    },

    // 新增角色 - 按钮点击事件
    addRoleBtn() {
      this.isEdit = false // 现在不是编辑状态
      this.showDialog = true // 弹窗出现
    },

    // 设置角色 - 分配权限 -点击事件
    async setRoles(roleId) {
      this.dialogVisible = true
      this.roleId = roleId

      const res = await getRoleIdAPI(roleId)
      if (!res.success) return this.message.error(res.message)
      this.roleIdsList = res.data.permIds // 角色相关的权限点id数组
    },
    // 分配权限点 -> 弹窗关闭事件
    roleDialogCloseFn() {
      this.dialogVisible = false
      this.roleIdsList = []
      this.$refs.assignPermission.$refs.tree.setCheckedKeys([]) // 把树形组件默认选中的项目清空
    },
    // 分配权限点 -> 确定事件
    async confirmFn(arr) {
      const res = await assignPermAPI({
        id: this.roleId,
        permIds: arr // 选中的权限点 - 数组
      })
      if (!res.success) return this.$message.error(res.message)
      this.$message.success(res.message)

      // 关闭弹窗
      this.roleDialogCloseFn()
    },

    // 编辑角色
    async editRoles(roleId) {
      this.isEdit = true
      const res = await getRoleIdAPI(roleId)
      this.roleForm = res.data
      this.showDialog = true
    },

    // 删除角色
    async delRoles(roleId) {
      const delRes = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 用户点击了取消，给用户进行提示
      if (delRes === 'cancel') return this.$message.info('您取消了删除')
      // 删除的逻辑
      const res = await deleteRoleAPI(roleId)
      // 删除失败的提示
      if (!res.success) return this.$message.error(res.message)
      // 删除成功的提示
      this.$message.success(res.message)
      // 重新获取数据
      this.getRolesListFn()

      if (this.rolesList.length <= 1) {
        this.query.page--
        if (this.query.page === 0) {
          this.query.page = 1
        }
      }
    },

    // 弹窗关闭 - 事件
    closeRoleFn() {
      this.roleForm = {
        name: '',
        description: ''
      }
      // 置空form
      this.$refs.roleForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  padding: 10px 30px;
}

.tab-pane {
  padding: 20px;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}
</style>

